<template>
  <div class="app-container">
    <div class="operation-container">
      <div class="filter-container">
        <el-form :inline="true">
          <el-form-item label="更新通知群">
            <el-select v-model="listQuery.groupId" filterable placeholder="全部" style="width: 260px">
              <el-option value="">全部</el-option>
              <el-option
                v-for="item in group"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="环境模板">
            <el-select v-model="listQuery.templateId" placeholder="全部" class="filter-item">
              <el-option value="">全部</el-option>
              <el-option
                v-for="item in template"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="更新人员">
            <el-select v-model="listQuery.userIds" filterable multiple placeholder="请选择更新人员">
              <el-option
                v-for="item in users"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="listQuery.status" placeholder="全部" class="filter-item">
              <el-option value="">全部</el-option>
              <el-option
                v-for="item in dict['sys_publish']"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button class="filter-item" type="primary" round icon="el-icon-search" @click="handleFilter">
              搜索
            </el-button>
            <el-button class="filter-item" round icon="el-icon-search" @click="handleReset">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-button class="filter-item" type="primary" round icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>
    <div class="operation-container">
      <el-table
        ref="dictTable"
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        row-key="id"
        fit
        stripe
        highlight-current-row
        @row-dblclick="handleInfo"
      >
        <el-table-column
          label="序号"
          type="index"
          :index="indexMethod"
        />
        <el-table-column width="360" label="更新通知群">
          <template slot-scope="props">
            <el-form>
              <el-form-item>
                <div>
                  <span style="font-weight: 600">{{ props.row.groupName }}</span> -
                  <span>{{ props.row.templateName }}</span>
                </div>
                <div>
                  <template v-for="(item,index) in dict['sys_mode_type']">
                    <el-tag v-if="item.value === props.row.mode" :key="'mode' + index" :type="item.listClass">{{ item.label }}</el-tag>
                  </template>
                  <template v-for="(item,index) in dict['sys_risk_type']">
                    <el-tag v-if="parseInt(item.value) === props.row.risk" :key="'risk' + index" :type="item.listClass">{{ item.label }}</el-tag>
                  </template>
                  <template v-for="(item,index) in dict['sys_data_type']">
                    <el-tag v-if="item.value === props.row.dataChanged" :key="'dataChanged' + index" :type="item.listClass">{{ item.label }}</el-tag>
                  </template>
                </div>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>

        <el-table-column prop="systemNames" label="更新系统" width="150">
          <template slot-scope="{row}">
            <template v-for="(item,index) in row.systemNames">
              <p :key="index">{{ index+1 }}.{{ item }}</p>
            </template>
          </template>
        </el-table-column>

        <el-table-column label="更新时间/结束时间" prop="onlineTime" width="180">
          <template slot-scope="{row}">
            <p><i class="el-icon-time margin-right-5" />{{ row.onlineTime | dateFormat }}</p>
            <p><i class="el-icon-time margin-right-5" />{{ row.onlineTime | dateFormatAdd(row.duration) }}</p>
          </template>
        </el-table-column>

        <el-table-column label="更新时长" align="center" prop="duration">
          <template slot-scope="{row}">
            <span>{{ row.duration }}分钟</span>
          </template>
        </el-table-column>

        <el-table-column prop="durationUser" label="更新人员">
          <template slot-scope="{row}">
            <template v-for="(item,index) in row.durationUser">
              <p :key="index"><i class="el-icon-user" />{{ item }}</p>
            </template>
          </template>
        </el-table-column>

        <el-table-column prop="influenceNames" label="影响系统" width="150">
          <template slot-scope="{row}">
            <template v-for="(item,index) in row.influenceNames">
              <p :key="index">{{ index+1 }}.{{ item }}</p>
            </template>
          </template>
        </el-table-column>

        <el-table-column label="状态" class-name="status-col" align="center" width="100">
          <template slot-scope="{row}">
            <div v-if="row.status === 'Y' && isStatus(row.onlineTime)">
              <template v-for="(item,index) in dict['sys_publish']">
                <el-tag v-if="item.value === row.status" :key="index" :type="item.listClass">{{ item.label }}</el-tag>
              </template>
            </div>
            <div v-else>
              <el-switch
                v-model="row.status"
                active-value="Y"
                inactive-value="N"
                inactive-color="#dfdfdf"
                @change="handleSwitch(row)"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="创建人" prop="createByName" />
        <el-table-column label="创建时间" prop="createTime" width="180">
          <template slot-scope="{row}">
            <i class="el-icon-time margin-right-5" />
            <span>{{ row.createTime | dateFormat }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="200" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button type="text" @click="handleInfo(row)">
              <i class="el-icon-edit" />详情
            </el-button>
            <el-button v-if="row.status !== 'Y'" type="text" @click="handleUpdate(row)">
              <i class="el-icon-edit" />修改
            </el-button>
            <el-button type="text" @click="handleDelete(row)">
              <i class="el-icon-delete" />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNumber" :limit.sync="listQuery.pageSize" @pagination="getList" />
    </div>

    <!-- 新增编辑通知 -->
    <el-dialog :title="textMap[dialogStatus]" width="800px" append-to-body :visible.sync="dialog">
      <el-form
        ref="dataForm"
        label-width="100px"
        :model="notice"
        :rules="rules"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="通知群名称" prop="groupId">
              <el-select v-model="notice.groupId" filterable style="width:100%">
                <el-option
                  v-for="item in group"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="更新时间" prop="onlineTime" style="width:100%">
              <el-date-picker
                v-model="notice.onlineTime"
                type="datetime"
                placeholder="选择日期时间"
              />
            </el-form-item>
            <el-form-item label="更新人员" prop="durationUserIds">
              <el-select v-model="notice.durationUserIds" multiple filterable placeholder="请选择更新人员" style="width:100%">
                <el-option
                  v-for="item in users"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="更新方式" prop="mode">
              <template v-for="(item,index) in dict['sys_mode_type']">
                <el-radio :key="index" v-model="notice.mode" :label="item.value">{{ item.label }}</el-radio>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新模板" prop="templateId">
              <el-select v-model="notice.templateId" class="filter-item">
                <el-option
                  v-for="item in template"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="更新时长" prop="duration">
              <el-input-number v-model="notice.duration" controls-position="right" :min="1" />
            </el-form-item>
            <el-form-item label="电联人员" prop="tellUserIds">
              <el-select v-model="notice.tellUserIds" multiple filterable placeholder="请选择电联人员">
                <el-option
                  v-for="item in users"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="反馈时间" prop="feedback">
              <el-input-number v-model="notice.feedback" controls-position="right" :min="1" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="风险等级" prop="risk">
          <template v-for="(item,index) in dict['sys_risk_type']">
            <el-radio :key="index" v-model="notice.risk" :label="parseInt(item.value)">{{ item.label }}</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="更新系统" prop="systemIds">
          <el-select v-model="notice.systemIds" multiple filterable placeholder="请选择更新系统" style="width:100%">
            <el-option
              v-for="item in system"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <div v-for="(item,index) in listCntents" :key="index">
          <el-form-item :label="index ===0 ?'更新内容':''" prop="listCntents">
            <el-input v-model="item.content" style="width: 80%" />
            <el-button v-if="index!==0" @click.prevent="removeDomain(item)">-</el-button>
            <el-button v-if="(index+1) === listCntents.length" @click="addDomain">+</el-button>
          </el-form-item>
        </div>
        <div v-for="(item,index) in listUrls" :key="'url' + index">
          <el-form-item :label="index === 0 ?'详情连接':''" prop="listUrls">
            <el-input v-model="item.content" style="width: 80%" />
            <el-button v-if="index !== 0" @click.prevent="removeDomainUrl(item)">-</el-button>
            <el-button v-if="(index+1) === listUrls.length" @click="addDomainUrl">+</el-button>
          </el-form-item>
        </div>
        <el-form-item label="通知人员" prop="noticeUserIds">
          <el-select v-model="notice.noticeUserIds" multiple filterable placeholder="请选择通知人员" style="width:100%">
            <el-option
              v-for="item in users"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="影响系统" prop="influenceIds">
          <el-select v-model="notice.influenceIds" multiple filterable placeholder="请选择影响系统" style="width:100%">
            <el-option
              v-for="item in system"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="数据库是否已变动" label-width="150px" prop="dataChanged">
              <el-radio-group v-model="notice.dataChanged" @change="showDateUser = !showDateUser">
                <template v-for="(item,index) in dict['sys_data_type']">
                  <el-radio :key="index" :label="item.value">{{ item.label }}</el-radio>
                </template>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="是否发布" prop="status">
              <template v-for="(item,index) in dict['sys_publish']">
                <el-radio :key="index" v-model="notice.status" :label="item.value">{{ item.label }}</el-radio>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="showDateUser" label="变动通知人员" prop="dateUserIds">
              <el-select v-model="notice.dateUserIds" multiple filterable placeholder="请选择变动通知人员">
                <el-option
                  v-for="item in users"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="推送时间" prop="pushTime">
              <el-date-picker
                v-model="notice.pushTime"
                type="datetime"
                placeholder="默认当前时间"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="notice.remark" maxlength="150" show-word-limit type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitForm">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogVisible"
      width="800"
      class="notice-info"
    >
      <div class="notice-info-itme">
        <span style="font-size:16px;font-weight: 600">{{ notice.groupName }}</span> -
        <span style="margin-right: 10px">{{ notice.templateName }}</span>
        <template v-for="(item,index) in dict['sys_mode_type']">
          <el-tag v-if="item.value === notice.mode" :key="'mode' + index" :type="item.listClass">{{ item.label }}</el-tag>
        </template>
        <template v-for="(item,index) in dict['sys_risk_type']">
          <el-tag v-if="parseInt(item.value) === notice.risk" :key="'risk' + index" :type="item.listClass">{{ item.label }}</el-tag>
        </template>
        <template v-for="(item,index) in dict['sys_data_type']">
          <el-tag v-if="item.value === notice.dataChanged" :key="'dataChanged' + index" :type="item.listClass">{{ item.label }}</el-tag>
        </template>
        <template v-for="(item,index) in dict['sys_publish']">
          <el-tag v-if="item.value === notice.status" :key="index" :type="item.listClass">{{ item.label }}</el-tag>
        </template>
      </div>
      <div class="notice-info-itme">
        <p class="notice-info-itme-title">更新时间</p>
        <span>{{ notice.onlineTime | dateFormat }}</span>
      </div>
      <div class="notice-info-itme">
        <p class="notice-info-itme-title">更新人员</p>
        <template v-for="(item,index) in notice.durationUser">
          <span :key="index"><i class="el-icon-user" />{{ item }}</span>
        </template>
      </div>
      <div class="notice-info-itme">
        <p class="notice-info-itme-title">更新系统</p>
        <template v-for="(item,index) in notice.systemNames">
          <span :key="index" class="padding-right-10">{{ index+1 }}.{{ item }}</span>
        </template>
      </div>
      <div class="notice-info-itme">
        <p class="notice-info-itme-title">电联人员</p>
        <template v-for="(item,index) in notice.tellUser">
          <span :key="index"><i class="el-icon-user" />{{ item }}</span>
        </template>
      </div>
      <div class="notice-info-itme">
        <p class="notice-info-itme-title">通知人员</p>
        <template v-for="(item,index) in notice.noticeUser">
          <span :key="index"><i class="el-icon-user" />{{ item }}</span>
        </template>
      </div>
      <div class="notice-info-itme">
        <p class="notice-info-itme-title">影响系统</p>
        <template v-for="(item,index) in notice.influenceNames">
          <span :key="index" class="padding-right-10">{{ index+1 }}.{{ item }}</span>
        </template>
      </div>
      <div class="notice-info-itme">
        <p class="notice-info-itme-title">数据库变动通知人员</p>
        <template v-for="(item,index) in notice.dateUser">
          <span :key="index"><i class="el-icon-user" />{{ item }}</span>
        </template>
      </div>
      <div class="notice-info-itme">
        <p class="notice-info-itme-title">更新内容</p>
        <template v-for="(item,index) in notice.contents">
          <p :key="index">{{ index+1 }}.{{ item }}</p>
        </template>
      </div>
      <div class="notice-info-itme">
        <p class="notice-info-itme-title">详情连接</p>
        <template v-for="(item,index) in notice.urls">
          <p :key="index">{{ index+1 }}.{{ item }}</p>
        </template>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { groupSearch } from '@/api/data/group'
import { templateSearch } from '@/api/data/template'
import { systemSearch } from '@/api/system'
import { userFetchList } from '@/api/user'
import { fetchList, create, update, deletes } from '@/api/data/notice'

import Pagination from '@/components/Pagination'
import { mapGetters } from 'vuex'
import { MessageBox } from 'element-ui'

export default {
  name: 'NoticeTable',
  components: {
    Pagination
  },
  data() {
    return {
      tableKey: 0,
      listLoading: false,
      list: undefined,
      dialogVisible: false,
      dialogUrl: undefined,
      total: 0,
      dialog: false,
      dialogStatus: undefined,
      showDateUser: false,
      group: [],
      template: [],
      users: [],
      system: [],
      listQuery: {
        pageNumber: 1,
        pageSize: 10,
        groupId: undefined,
        templateId: undefined,
        userIds: [],
        status: ''
      },
      textMap: {
        update: '修改通知',
        create: '添加通知'
      },
      listCntents: [{
        content: ''
      }],
      listUrls: [{
        content: ''
      }],
      notice: {
        id: undefined,
        contents: [],
        dataChanged: 'N',
        dateUserIds: [],
        duration: 10,
        durationUserIds: [],
        feedback: 5,
        groupId: undefined,
        influenceIds: [],
        mode: 'N',
        noticeUserIds: [],
        onlineTime: undefined,
        remark: undefined,
        risk: 0,
        systemIds: [],
        tellUserIds: [],
        templateId: undefined,
        urls: [],
        status: 'N',
        pushTime: undefined
      },
      rules: {
        groupId: [
          { required: true, trigger: 'blur', message: '请选择通知群' }
        ],
        onlineTime: [
          { required: true, trigger: 'blur', message: '请选择更新时间' }
        ],
        durationUserIds: [
          { required: true, trigger: 'blur', message: '请选择更新人员' }
        ],
        templateId: [
          { required: true, trigger: 'blur', message: '请选择更新模板' }
        ],
        systemIds: [
          { required: true, trigger: 'blur', message: '请选择更新系统' }
        ],
        noticeUserIds: [
          { required: true, trigger: 'blur', message: '请选择通知人员' }
        ]
      },
      multipleSelection: []
    }
  },
  computed: {
    ...mapGetters([
      'dict'
    ])
  },
  created() {
    this.queryList()
    this.getList()
  },
  methods: {
    queryList() {
      groupSearch().then(response => {
        this.group = response.data
      })
      templateSearch().then(response => {
        this.template = response.data
      })
      userFetchList({ pageNumber: 1, pageSize: 999, status: 'Y' }).then(response => {
        this.users = response.data.list
      })
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.2 * 1000)
      })
    },
    // 查询事件
    handleFilter() {
      this.listQuery.pageNumber = 1
      this.getList()
    },
    indexMethod(index) {
      return index + 1
    },
    // 重置查询事件
    handleReset() {
      this.listQuery = {
        pageNumber: 1,
        pageSize: 10,
        title: undefined,
        type: undefined,
        status: undefined
      }
    },
    // 创建事件
    handleCreate() {
      this.resetFields()
      this.dialog = true
      this.dialogStatus = 'create'
    },
    // 修改事件
    handleUpdate(row) {
      this.handleInit(row)
      this.notice = Object.assign({}, row) // copy obj
      this.dialog = true
      this.dialogStatus = 'update'
    },
    handleInfo(row) {
      this.handleInit(row)
      this.notice = Object.assign({}, row) // copy obj
      this.dialogVisible = true
    },
    handleInit(row) {
      this.resetFields()
      this.showDateUser = row.dataChanged === 'Y'
      this.listCntents = this.dateForEach(row.contents)
      this.listUrls = this.dateForEach(row.urls)
    },
    dateForEach(list, isContent = false) {
      if (list.length > 0) {
        const contentList = []
        if (isContent) {
          list.forEach(function(itme) {
            if (!itme.content || itme.content === '') {
              return
            }
            contentList.push(itme.content)
          })
        } else {
          list.forEach(function(itme) {
            contentList.push({ content: itme })
          })
        }
        return contentList
      }
      return [{
        content: '' }
      ]
    },
    // 删除事件
    handleDelete(row) {
      deletes(row.id).then(() => {
        this.getList()
        this.$notify({
          title: '删除成功！',
          type: 'success',
          duration: 2000
        })
      })
    },
    // 状态转换事件
    handleSwitch(row) {
      if (row.status === 'N') {
        row.status = 'Y'
      } else {
        MessageBox.confirm('是否确认发布，注意：发布后将会通知对应钉钉群！', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          update(row.id, row).then(() => {
            this.$notify({
              title: '发布成功！',
              type: 'success',
              duration: 2000
            })
            row.status = 'Y'
          })
        }).catch(function() {
          row.status = 'N'
        })
      }
    },
    submitForm() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.notice.contents = this.dateForEach(this.listCntents, true)
          this.notice.urls = this.dateForEach(this.listUrls, true)
          if (this.notice.contents.length <= 0) {
            this.$message.error('更新内容不能为空!')
            return
          }
          if (this.notice.id) {
            update(this.notice.id, this.notice).then(() => {
              this.dialog = false
              this.getList()
              this.$notify({
                title: '修改成功！',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            create(this.notice).then(() => {
              this.dialog = false
              this.getList()
              this.$notify({
                title: '新增成功！',
                type: 'success',
                duration: 2000
              })
            })
          }
        }
      })
    },
    isStatus(date) {
      const minutes = new Date().getTime()
      const dateMinutes = new Date(date).getTime()
      return dateMinutes - minutes <= 0
    },
    resetFields() {
      systemSearch().then(response => {
        this.system = response.data
      })
      this.notice = {
        id: undefined,
        contents: [],
        dataChanged: 'N',
        dateUserIds: [],
        duration: 10,
        durationUserIds: [],
        feedback: 5,
        groupId: undefined,
        influenceIds: [],
        mode: 'N',
        noticeUserIds: [],
        onlineTime: undefined,
        remark: undefined,
        risk: 0,
        systemIds: [],
        tellUserIds: [],
        templateId: undefined,
        urls: [],
        status: 'N',
        pushTime: undefined
      }
      this.listCntents = [{
        content: ''
      }]
      this.listUrls = [{
        content: ''
      }]
      this.showDateUser = false
      if (this.$refs['dataForm'] !== undefined) {
        this.$refs['dataForm'].resetFields()
      }
    },
    addDomain() {
      this.listCntents.push({ 'content': '' })
    },
    removeDomain(item) {
      const index = this.listCntents.indexOf(item)
      if (index !== -1) {
        this.listCntents.splice(index, 1)
      }
    },
    addDomainUrl() {
      this.listUrls.push({ 'content': '' })
    },
    removeDomainUrl(item) {
      const index = this.listUrls.indexOf(item)
      if (index !== -1) {
        this.listUrls.splice(index, 1)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.el-tag{
  margin-right: 10px;
}
.padding-right-10{
  padding-right: 10px;
}
.notice-info {
  .el-dialog__header {
    display: none;
  }
  .el-dialog__body {
    padding: 30px!important;
  }
  .notice-info-itme {
    padding: 10px;
  }
  .notice-info-itme-title {
    color: #99a9bf;
  }
}
</style>
